package com.yljk.yljkproject.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.config.BaseUrl;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.utils.ALog;
import com.yljk.yljkproject.MyApplication;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "Android_YLJK";
    private String code = null; //用户返回码
    private String getTokenUrl = null; // token url
    private String refresh_url = null; // freshtoken url
    private String request_user_url = null; // requestUserInfo url

    public static boolean changeImageAvator = false;
    private static HttpCallBack<String> callBack = null;

    public static void setCallBack(HttpCallBack<String> c) {
        callBack = c;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        WeChatUtils.api.registerApp(ConfigureConstants.WECHAT_ID);
        MyApplication.iwxapi.handleIntent(getIntent(), this);
    }

    //微信请求相应
    @Override
    public void onReq(BaseReq baseReq) {

    }
    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {
        code = null;
        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM){
            //唤起小程序
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
            String extraData =launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
        }
        switch (resp.errCode) {
            //微信授权调用成功
            case BaseResp.ErrCode.ERR_OK:
                    if (resp instanceof SendAuth.Resp) {
                        SendAuth.Resp newResp = (SendAuth.Resp) resp;
                        //获取微信传回的code
                        code = newResp.code;

                        if (changeImageAvator){
                            changeImageAvator = false;
                            callBack.onSuccess(code,200);
                        }else{
                            ALog.d(TAG, "onResp: "+code);
                            Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
                            intent.putExtra("wechatCode",code);         //向广播接收器传递数据
                            sendBroadcast(intent);      //发送广播
                        }

                    }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消微信授权", Toast.LENGTH_SHORT).show();
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "拒绝微信授权", Toast.LENGTH_SHORT).show();
                //发送被拒绝
                break;
            default:
                Toast.makeText(this, "取消微信授权", Toast.LENGTH_SHORT).show();
                //发送返回
                break;
        }
        finish();
    }

    /**
     * 请求用户token
     * @param code 请求结果返回码
     */
//    private void requestUserToken(String code) {
//        NetWorkUtils.initNetWorkUtils(this).get(getTokenUrl, new NetWorkCallBack() {
//            @Override
//            public void onSuccess(String resultMsg, int code) {
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(resultMsg);
//                    String access_token = jsonObject.getString("access_token");
//                    String refresh_token = jsonObject.getString("refresh_token");
//                    String openid = jsonObject.getString("openid");
//                    ALog.d(TAG, "run1: " + code);
//                    ALog.d(TAG, "run1: " + access_token);
//                    ALog.d(TAG, "run1: " + refresh_token);
//                    ALog.d(TAG, "run1: " + openid);
//                    //获取refresh_token
//                    refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?" +
//                            "appid=" + ConfigureConstants.WECHAT_ID +
//                            "&grant_type=refresh_token" +
//                            "&refresh_token=" + refresh_token;
//                }catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(String failureMsg) {
//
//            }
//
//            @Override
//            public void onException(Exception exceptionMsg) {
//
//            }
//        });
////        OkGo.<String>get(getTokenUrl).execute(new StringCallback() {
////            @Override
////            public void onSuccess(Response<String> response) {
////                String s = response.body();
////                JSONObject jsonObject = null;
////                try {
////                    jsonObject = new JSONObject(s);
////                    String access_token = jsonObject.getString("access_token");
////                    String refresh_token = jsonObject.getString("refresh_token");
////                    String openid = jsonObject.getString("openid");
////                    ALog.d(TAG, "run1: " + code);
////                    ALog.d(TAG, "run1: " + access_token);
////                    ALog.d(TAG, "run1: " + refresh_token);
////                    ALog.d(TAG, "run1: " + openid);
////                    //获取refresh_token
////                    refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?" +
////                            "appid=" + ConfigureConstants.WECHAT_ID +
////                            "&grant_type=refresh_token" +
////                            "&refresh_token=" + refresh_token;
////                } catch (JSONException e) {
////                    e.printStackTrace();
////                }
////            }
////        });
//    }

    /**
     * OKgo请求用户refreshToken
     * @param refresh_url http url 地址
     * @param code 返回码
     */
//    private void requestUserFreshToken(String refresh_url, String code) {
//        NetWorkUtils.initNetWorkUtils(this).get(refresh_url, new NetWorkCallBack() {
//            @Override
//            public void onSuccess(String resultMsg, int code) {
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(resultMsg);
//                    String access_token = jsonObject.getString("access_token");
//                    String refresh_token = jsonObject.getString("refresh_token");
//                    String openid = jsonObject.getString("openid");
//                    String scope = jsonObject.getString("scope");
//                    ALog.d(TAG, "run2: " + code);
//                    ALog.d(TAG, "run2: " + access_token);
//                    ALog.d(TAG, "run2: " + refresh_token);
//                    ALog.d(TAG, "run2: " + openid);
//                    ALog.d(TAG, "run2: " + scope);
//                    String[] split = scope.split(",");
//                    //获取用户openID
//                    request_user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="
//                            + access_token
//                            + "&openid="
//                            + openid;
//                    //OKGO请求用户信息
//                    requestUserName(request_user_url);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(String failureMsg) {
//
//            }
//
//            @Override
//            public void onException(Exception exceptionMsg) {
//
//            }
//        });
////        OkGo.<String>get(refresh_url).execute(new StringCallback() {
////            @Override
////            public void onSuccess(Response<String> response) {
////                String s = response.body();
////                JSONObject jsonObject = null;
////                try {
////                    jsonObject = new JSONObject(s);
////                    String access_token = jsonObject.getString("access_token");
////                    String refresh_token = jsonObject.getString("refresh_token");
////                    String openid = jsonObject.getString("openid");
////                    String scope = jsonObject.getString("scope");
////                    ALog.d(TAG, "run2: " + code);
////                    ALog.d(TAG, "run2: " + access_token);
////                    ALog.d(TAG, "run2: " + refresh_token);
////                    ALog.d(TAG, "run2: " + openid);
////                    ALog.d(TAG, "run2: " + scope);
////                    String[] split = scope.split(",");
////                    //获取用户openID
////                    request_user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="
////                            + access_token
////                            + "&openid="
////                            + openid;
////                    //OKGO请求用户信息
////                    requestUserName(request_user_url);
////                } catch (JSONException e) {
////                    e.printStackTrace();
////                }
////            }
////        });
//    }

    /**
     *OKGO请求用户信息
     * @param request_user_url http url地址
     */
//    private void requestUserName(String request_user_url) {
////        OkGo.<String>get(request_user_url).execute(new StringCallback() {
////            @Override
////            public void onSuccess(Response<String> response) {
////                ALog.d(TAG, "onSuccess: "+response.body());
////            }
////        });
//    }
}
